package com.tomowork.controller;

import com.mysql.fabric.Server;
import com.tomowork.commons.ServerResponse;
import com.tomowork.entity.User;
import com.tomowork.service.IUserService;
import com.tomowork.shiroRealm.MyRealm;
import com.tomowork.utils.CookieUtil;
import com.tomowork.utils.ItzixiCaptcha;
import com.tomowork.utils.RedisOperator;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService iUserService ;
    @Autowired
    private MyRealm myRealm ;
    @Autowired
    private RedisOperator redisOperator ;
    @Autowired
    private ItzixiCaptcha itzixiCaptcha ;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ServerResponse login(HttpServletResponse response,HttpServletRequest request,String username,
                                String password,@RequestParam(name = "rememberMe",defaultValue = "0") Integer rememberMe,String code){
        if(StringUtils.isBlank(username)){
            return ServerResponse.fail("用户名不可以为空");
        }
        if(StringUtils.isBlank(password)){
            return ServerResponse.fail("密码不能为空") ;
        }
        if(!itzixiCaptcha.validate(request,response,code)){
            return ServerResponse.fail("验证码错误") ;
        }
        Subject subject = SecurityUtils.getSubject() ;
        //表示向password上面撒盐加密
//        String saltMd5Password = new Md5Hash(password,username,10).toString() ;
        UsernamePasswordToken token = new UsernamePasswordToken(username,password) ;
        if (rememberMe==1){
            token.setRememberMe(true);
        }
        try{
            subject.login(token); //进行登陆的时候会找到自定的Realm,即com.tomowork.shiroRealm.MyRealmH这个类进行认证和授权
        }catch (UnknownAccountException e){
            return ServerResponse.fail("账号不存在") ;
        }catch (DisabledAccountException e){
            return ServerResponse.fail("账号不可用") ;
        }catch (IncorrectCredentialsException e){
            return ServerResponse.fail("密码错误");
        }catch (RuntimeException e){
            System.out.println("********************"+e);
            return ServerResponse.fail("系统错误，可能要杀程序员祭天了");
        }
        return ServerResponse.success("登录成功") ;
    }
    //进行用户的注册
    @PostMapping("/regist")
    public ServerResponse regist(User user){
        String password = user.getPassword() ; //这里要用到加密之前的密码
        boolean isSave = iUserService.save(user);
        if(isSave){
            //如果用户注册成功，则自动登录
            Subject subject = SecurityUtils.getSubject() ;
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),password) ;
            subject.login(token);
            return ServerResponse.success() ;
        }else{
            return ServerResponse.fail() ;
        }
    }
    //获取验证码
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        itzixiCaptcha.generate(request, response);
    }

    //验证用户名是否已经存在
    @RequestMapping(value = "/checkExist",method = RequestMethod.GET)
    public ServerResponse checkExist(String username){
        boolean b = iUserService.checkExist(username);
        if(b){ //表示用户名已经存在
            return ServerResponse.fail() ;
        }
        //这里只需要成功的编码
        return ServerResponse.success() ;
    }


    //清除用户权限缓存
    @RequestMapping("/clearCache")
    public ServerResponse clearCache(){
        myRealm.clearCache();
        return ServerResponse.success() ;
    }


    //测试cookie
    @RequestMapping("/setCookie")
    public ServerResponse setCookie(HttpServletRequest request, HttpServletResponse response){
        CookieUtil.setCookie(request,response,"testCookie","test_cookie_sdsada",7*24*60*60) ;
        return ServerResponse.success("cookie设置成功") ;
    }
    @RequestMapping("/getCookie")
    public ServerResponse getCookie(HttpServletRequest request, HttpServletResponse response){
        String testCookie = CookieUtil.getCookieValue(request, "testCookie");
        return ServerResponse.success("取得cookie:"+testCookie) ;
    }

    //测试redisTemplate

    @RequestMapping("/setKey")
    public ServerResponse setKey(){
        redisOperator.set("testTeplate","hello redis template");
        return ServerResponse.success("redis设置成功") ;
    }
    @RequestMapping("/getKey")
    public ServerResponse getKey(){
        return ServerResponse.success("取得cookie:"+redisOperator.get("testTeplate")) ;
    }
}
